package com.mars.common.fegin;

import com.ag.exception.CodeException;
import com.ag.exception.CommonCode;
import com.ag.exception.SysException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {
	@Override
	public Exception decode(String methodKey, Response response) {
		try {
			String errorContent = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
			JSONObject jsonObject = JSONObject.parseObject(errorContent);
			if(jsonObject.containsKey("code")) {
				int code = jsonObject.getIntValue("code");
				String msg = jsonObject.getString("msg");
				return new CodeException(code, msg);
			} else if(jsonObject.containsKey("status")) {
				return new CodeException(CommonCode.ENTITY_NOTFOUND_EXCEPTION, Joiner.on("-").skipNulls().join(jsonObject.get("status"), jsonObject.get("error")));
			}
			
			return new SysException("位置错误, 请重试");
		} catch (Exception e) {
			log.error("处理 FeignClient 异常错误");
			e.printStackTrace();
			return new CodeException(-1, e.getLocalizedMessage());
		}
	}
}
